#include "TCPNet.h"

#include "Poco/Timespan.h"
#include "Poco/Net/NetException.h"
#include <iostream>
/*********************************************************/
void TCPConnection::setTCPNet(TCPNet* net)
{
	TCPConnection::net = net;
}
/*********************************************************/
void TCPConnection::run()
{
	Poco::Net::StreamSocket ss = socket();
}
/*********************************************************/
TCPConnection* TCPConnectionFactory::createConnection(const Poco::Net::StreamSocket& socket)
{
	TCPConnection* conn = new( TCPConnection )( socket );
	conn->setTCPNet(masterClass);
	return( conn );
}
/*********************************************************/
void TCPNet::connect(const std::string& host, const int& port)
{
	sender = new( Poco::Net::StreamSocket );
	try {
		sender->connect(Poco::Net::SocketAddress(host,port), Poco::Timespan(15,0));
	} catch(Poco::Net::NetException& e) {
		std::cout << "Exception caught: " <<  e.what() << std::endl;
	}
}
/*********************************************************/
void TCPNet::disconnect()
{
	sender->shutdown();
}
/*********************************************************/
void TCPNet::enqueue(const std::string& msg)
{
	mQueue.lock();
	queue.push_back(msg);
	mQueue.unlock();
}
/*********************************************************/
TCPNet::TCPNet(const std::string& host, const int& port)
{
	localAddr = Poco::Net::SocketAddress(host, port);
	listener = new( Poco::Net::ServerSocket );
	listener->bind(localAddr);

	listener->listen();
	factory = new( TCPConnectionFactory )(this);
	tcpServer = new( Poco::Net::TCPServer )(factory, tPool, (*listener));
	tcpServer->start();
}
/*********************************************************/
TCPNet::~TCPNet()
{
	tcpServer->stop();
}
/*********************************************************/